package com.catalina.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.catalina.entity.User;
import com.catalina.service.UserService;

@Controller
public class UserController {
	@Autowired
	private UserService userService;

	@RequestMapping("/getSession")
	public String getSession(HttpServletRequest request) {
		return "layout";
	}

	/*
	 * @RequestMapping("/getSession")
	 * 
	 * @ResponseBody public Map<String, String> getSession(HttpServletRequest
	 * request) { Object object = request.getSession().getAttribute("user");
	 * Map<String, String> map = new HashMap<>(); if (object != null) {
	 * map.put("url", "/home"); } else { map.put("url", "/login"); } return map;
	 * }
	 */

	@RequestMapping("/name")
	@ResponseBody
	public Map<String, Object> getName(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		String name = null;
		Map<String, Object> map = new HashMap<>();
		if (user != null) {
			name = user.getUsername();
			map.put("flag", 1);
			map.put("name", name);
		} else {
			map.put("flag", 0);
			map.put("url", "/login");
		}
		return map;
	}

	// login
	@RequestMapping("/hello")
	@ResponseBody
	public Map<String, Object> hello(HttpServletRequest request, String username, String password) {
		User user = userService.select(username, password);
		Map<String, Object> map = new HashMap<>();
		if (user != null) {
			request.getSession().setAttribute("user", user);
			map.put("flag", 1);
			map.put("url", "/home");
		} else {
			map.put("flag", 0);
		}
		return map;
	}

	// signout
	@RequestMapping("/signout")
	public String signout(HttpServletRequest request) {
		Object object = request.getSession().getAttribute("user");
		if (object != null) {
			request.getSession().removeAttribute("user");
			request.getSession().invalidate();
		}
		return "redirect:/login";
	}

	@RequestMapping("/json1")
	@ResponseBody
	public Map<String, Object> world1(Integer page, Integer rows, String name, String sort, String order) {// 得到全部数据
		Map<String, Object> map = new HashMap<>();
		List<User> users = userService.selectList(page, rows, name, sort, order);
		Integer num = userService.getTotal(name);
		map.put("rows", users);
		map.put("total", num);
		return map;
	}

	@RequestMapping("/total")
	@ResponseBody
	public Integer getTotal(String name) {// 得到总数
		Integer num = userService.getTotal(name);
		return num;
	}

	@RequestMapping("/json2")
	@ResponseBody
	public List<User> world2(Integer page, Integer rows, String name, String sort, String order) {// 得到datagrid数据
		List<User> users = userService.selectList(page, rows, name, sort, order);
		return users;
	}

	@RequestMapping("/register")
	@ResponseBody
	public Map<String, String> register() {
		Map<String, String> map = new HashMap<>();
		map.put("url", "/regist");
		return map;
	}

	@RequestMapping("/add")
	@ResponseBody
	public Map<String, String> insert(HttpServletRequest request, User user) {
		userService.insert(user);
		request.getSession().setAttribute("user", user);
		Map<String, String> map = new HashMap<>();
		map.put("url", "/home");
		return map;
	}

	@RequestMapping("/delete")
	public void delete(@RequestParam("number") int num) {
		System.out.println(num);
		userService.delete(num);
	}

	@RequestMapping("/dellist")
	@ResponseBody
	public Map<String, Integer> deleteList(@RequestParam("Ids") String ids) {
		Integer num = userService.deleteList(ids);
		Map<String, Integer> map = new HashMap<String, Integer>();
		if (num > 0) {
			map.put("result", 1);
		} else {
			map.put("result", 0);
		}
		return map;
	}

	@RequestMapping("/update")
	@ResponseBody
	public User update(User user) {
		userService.update(user);
		return user;
	}

	/*
	 * POI导出excel 2015.11.27
	 */
	@RequestMapping("/printPage")
	public void printPage(HttpServletResponse response, String title, Integer number, Integer size, String name,
			String sort, String order) throws IOException {// 导出excel
		String[] arrTitle = title.split(",");
		List<User> users = userService.selectList(number, size, name, sort, order);

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = simpleDateFormat.format(new Date());

		Workbook workbook = userService.exportToExcel(arrTitle, fileName, users);

		// 根据文件路径名直接导出到硬盘上 2015.11.27
		/*
		 * String file = "D:/" + fileName + ".xlsx"; FileOutputStream
		 * fileOutputStream = new FileOutputStream(file);
		 * workbook.write(fileOutputStream); fileOutputStream.close();
		 */

		// 提示下载
		String filename = fileName + ".xlsx";
		response.reset();// 设置头信息
		response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
		response.setHeader("Content-Type", "application/vnd.ms-excel; charset=UTF-8");
		OutputStream outputStream = response.getOutputStream();
		workbook.write(outputStream);
		outputStream.flush();
		outputStream.close();

	}

	@RequestMapping("/upload")
	@ResponseBody
	public Map<String, String> upload(HttpServletRequest request, MultipartFile file) {
		// springMVC上传文件
		String path = request.getServletContext().getRealPath("/image");

		/*
		 * 使用commons fileupload上传文件 DiskFileItemFactory diskFileItemFactory =
		 * new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new
		 * ServletFileUpload(diskFileItemFactory); List<FileItem> fileItems =
		 * servletFileUpload.parseRequest(request); Iterator<FileItem>
		 * fileIterator = fileItems.iterator(); while(fileIterator.hasNext()){
		 * FileItem fileItem = fileIterator.next(); String fileName =
		 * fileItem.getName(); if(fileName != null){ File saveFile = new
		 * File(path, fileName); try { fileItem.write(saveFile); } catch
		 * (Exception e) { e.printStackTrace(); } } }
		 */
		String fileName = file.getOriginalFilename();
		File saveFile = new File(path, fileName);
		try {
			file.transferTo(saveFile);
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}

		Map<String, String> map = new HashMap<>();
		String src = "image" + File.separator + fileName;
		map.put("src", src);
		return map;
	}

}
